package com.wl.mvi.home

import androidx.lifecycle.viewModelScope
import com.wl.lib.mvi.BaseViewModel
import com.wl.lib.mvi.IUiIntent
import com.wl.lib.mvi.postEvent
import com.wl.lib.mvi.setState
import com.wl.mvi.home.model.repository.HomeRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch


// Created by wangliang on 2024/4/25.

class HomeViewModel : BaseViewModel<HomeIntent, HomeEvent>() {
    private val homeRepo: HomeRepository = HomeRepository()

    // 为了避免过度重绘，所以状态尽量分拆
    val bannerState = MutableStateFlow(BannerUiState())
    val detailState = MutableStateFlow(DetailUiState())


    private var curDetailPage: Int = 0 // 加载 detail 列表的当前页

    override fun handleIntent(intent: IUiIntent) {
        when (intent) {
            HomeIntent.GetBanner -> {
                requestDataWithFlow(
                    firstLoad = true,
                    showLoading = true,
                    request = { homeRepo.getWanData() },
                    successCallback = {
                        bannerState.setState {
                            copy(banners = it)
                        }
                    }
                )
            }

            is HomeIntent.GetDetail -> {
                requestDataWithFlow(
                    request = { homeRepo.getArticle(curDetailPage) },
                    successCallback = {
                        detailState.setState {
                            copy(article = it)
                        }

                        curDetailPage = it.curPage
                    }, failCallback = {
                        uiEvent.postEvent(HomeEvent.DetailNetError)
                    }
                )
            }

            is HomeIntent.TestIntent -> {
                viewModelScope.launch {
                    delay(5000)
                    uiEvent.postEvent(HomeEvent.TestEvent("test event"))
                }
            }
        }
    }
}
